package com.xlinur.android.moviecatalog;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.xlinur.android.moviecatalog.R;


public class MovieList extends ListActivity {
	public class Settings implements Cloneable {
		public String mOrder;
		public String mFilter;

		public Object clone() {
			try {
				return super.clone();
			} catch (CloneNotSupportedException e) {
				return null;
			}
		}

		public boolean equals(Settings o) {
			boolean result = true;
			result = result && this.mOrder.equals(o.mOrder);
			if (mFilter != null) {
				result = result && this.mFilter.equals(o.mFilter);
			} else {
				result = result && this.mFilter == o.mFilter;
			}
			return result;
		}
	}

	private static final int ALERT_DELETE = 1;
	private static Settings mSettings;
	public static Cursor mCursor;
	public static String mCurId;
	public static String mCurTitle;

	private void getPreferencesView() {
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(getBaseContext());
		mSettings.mOrder = prefs.getString("viewSort", getResources()
				.getString(R.string.order))
				+ " "
				+ prefs.getString("viewSortDir",
						getResources().getString(R.string.orderDir));

		mSettings.mFilter = " 1=1";
		String val;
		String defAll = getResources().getString(R.string.view_all);
		val = prefs.getString("viewGenre", defAll);
		if (!val.equals(defAll)) {
			mSettings.mFilter += " AND genre LIKE \"%" + val + "%\"";
		}
		val = prefs.getString("viewVideo", defAll);
		if (!val.equals(defAll)) {
			mSettings.mFilter += " AND video = \"" + val + "\"";
		}
		val = prefs.getString("viewAudio", defAll);
		if (!val.equals(defAll)) {
			mSettings.mFilter += " AND audio = \"" + val + "\"";
		}
		if (mSettings.mFilter.equals(" 1=1")) {
			mSettings.mFilter = null;
		}
	}

	private static String getFileSize(String str) {
		try {
			float string = Long.parseLong(str);
			String[] format = new String[] { "b", "KB", "MB", "GB", "TB" };
			int i = 0;
			while (i < format.length && string >= 1024) {
				string = Math.round(string / 1024 * 100);
				string = string / 100;
				i++;
			}
			return Float.toString(string) + " " + format[i];
		} catch (NumberFormatException e) {
			return str;
		}
	}

	private void showMovieList() {
		mCursor = MovieCatalog.db
				.getMovies(mSettings.mOrder, mSettings.mFilter);
		startManagingCursor(mCursor);
		
		SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this,
				R.layout.movie_item, mCursor, new String[] {
						MovieCatalog.Movie[0], MovieCatalog.Movie[2],
						MovieCatalog.Movie[5], MovieCatalog.Movie[6],
						MovieCatalog.Movie[7], MovieCatalog.Movie[8] },
				new int[] { R.id._id, R.id.title, R.id.filesize, R.id.video,
						R.id.audio, R.id.genre });

		class ShowViewBinder implements SimpleCursorAdapter.ViewBinder {
			private static final int SIZE_COLUMN = 5;

			// @Override
			public boolean setViewValue(View view, Cursor cursor,
					int columnIndex) {
				TextView tv = (TextView) view;
				if (columnIndex == SIZE_COLUMN) {
					tv.setText(getFileSize(cursor.getString(SIZE_COLUMN)));
				} else {
					tv.setText(cursor.getString(columnIndex));
				}
				return true;
			}
		}
		mAdapter.setViewBinder(new ShowViewBinder());
		setListAdapter(mAdapter);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mSettings = new Settings();
		setContentView(R.layout.movie_list);
		getListView().setOnCreateContextMenuListener(this);
		MovieCatalog.db = new MovieDatabase(this);
		MovieCatalog.db.open();
		getPreferencesView();
		showMovieList();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (MovieCatalog.db != null) {
			MovieCatalog.db.close();
		}
	}

	@Override
	public void onStart() {
		super.onStart();
		Settings oldSettings = (Settings) mSettings.clone();
		getPreferencesView();
		if (!mSettings.equals(oldSettings)) {
			showMovieList();
		}
	}
	
	
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		Cursor cursor = (Cursor) getListAdapter().getItem(position);
		if (cursor != null) {
			mCurId = cursor.getString(0);
			mCurTitle = cursor.getString(2);
			Intent viewActivity = new Intent(getBaseContext(),
					MovieView.class);
			startActivity(viewActivity);
		}
	}
	 
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.movie_list, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.list_menu_add: {
			mCurId = "";
			Intent editorActivity = new Intent(getBaseContext(),
					MovieEditor.class);
			startActivity(editorActivity);
			return true;
		}
		case R.id.list_menu_view: {
			Intent viewActivity = new Intent(getBaseContext(),
					PreferencesView.class);
			startActivity(viewActivity);
			return true;
		}
		case R.id.list_menu_sync_csv_import: {
			Intent importActivity = new Intent(getBaseContext(),
					MovieImportCSV.class);
			startActivity(importActivity);
			return true;
		}
		case R.id.list_menu_sync_csv_export: {
			Intent exportActivity = new Intent(getBaseContext(),
					MovieExportCSV.class);
			startActivity(exportActivity);
			return true;
		}
		case R.id.list_menu_preferences: {
			Intent preferencesActivity = new Intent(getBaseContext(),
					Preferences.class);
			startActivity(preferencesActivity);
			return true;
		}
		}
		return false;
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View view,
			ContextMenuInfo menuInfo) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.movie_list_context, menu);
		AdapterView.AdapterContextMenuInfo info;
		try {
			info = (AdapterView.AdapterContextMenuInfo) menuInfo;
		} catch (ClassCastException e) {
			return;
		}
		Cursor cursor = (Cursor) getListAdapter().getItem(info.position);
		if (cursor == null) {
			return;
		}

		menu.setHeaderTitle(cursor.getString(2));
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterView.AdapterContextMenuInfo info;
		try {
			info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
		} catch (ClassCastException e) {
			return false;
		}
		Cursor cursor = (Cursor) getListAdapter().getItem(info.position);
		if (cursor == null) {
			return false;
		}
		mCurId = cursor.getString(0);
		mCurTitle = cursor.getString(2);
		switch (item.getItemId()) {
		case R.id.list_menu_context_edit: {
			Intent editorActivity = new Intent(getBaseContext(),
					MovieEditor.class);
			startActivity(editorActivity);
			return true;
		}
		case R.id.list_menu_context_delete: {
			showDialog(ALERT_DELETE);
			return true;
		}
		}
		return false;
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case ALERT_DELETE:
			return new AlertDialog.Builder(this)
					.setMessage(R.string.message_confirm_delete)
					.setPositiveButton(R.string.button_yes,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									if (MovieCatalog.db.deleteMovie(mCurId) == 1) {
										Toast.makeText(
												getApplicationContext(),
												getString(
														R.string.message_movie_delete_success)
														.replace("{1}",
																mCurTitle),
												MovieCatalog.MESSAGE_TIME)
												.show();
										mCursor.requery();
									} else {
										Toast.makeText(
												getApplicationContext(),
												getString(
														R.string.message_movie_delete_fail)
														.replace("{1}",
																mCurTitle),
												MovieCatalog.MESSAGE_TIME)
												.show();
									}
								}
							})
					.setNegativeButton(R.string.button_no,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {

								}
							}).create();
		default:
			break;
		}
		return null;
	}
}